package com.codeark.appengine;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;

import org.apache.commons.lang.StringUtils;
import org.json.simple.JSONValue;

import com.google.appengine.api.urlfetch.HTTPResponse;
import com.google.appengine.api.urlfetch.URLFetchService;
import com.google.common.io.ByteStreams;
import com.google.common.io.CharStreams;
import com.google.common.io.InputSupplier;
import com.google.inject.Inject;


/**
 * 
 * @author Yaniv Kessler (yaniv at codeark dot com)
 *
 */
public class JsonUrlFetchServiceFacade extends AbstractUrlFetchServiceFacade<Object> {

	@Inject
	public JsonUrlFetchServiceFacade(URLFetchService web) {
		super(web);
	}

	protected Object convertResponse(HTTPResponse response) throws IOException {
		InputSupplier<ByteArrayInputStream> iss = ByteStreams.newInputStreamSupplier(response.getContent());
		InputSupplier<InputStreamReader> reader = CharStreams.newReaderSupplier(iss, Charset.forName("utf8"));
		String raw = CharStreams.toString(reader);
		if (StringUtils.isBlank(raw))
			return null;

		return JSONValue.parse(raw);
	}
}
